/**
 * 
 */
package com.hk.Mgr.web.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.sys.SysModuleReq;
import com.hk.Mgr.web.message.sys.SysModuleRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.HqlFilter;
import com.hk.commons.entity.sys.SysModule;
import com.hk.commons.entity.sys.SysModuleResource;
import com.hk.service.sys.ISysModule;
import com.hk.service.sys.ISysModuleResource;
import com.hk.service.sys.ISysResource;
import com.hk.service.sys.ISysRoleModules;




/**
 * @author baiht 系统模块实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/SysModuleCtrl")
public class SysModuleCtrl extends BaseCtrl {

	@Autowired
	private ISysModule sysModuleService;
	
	@Autowired
	private ISysModuleResource sysModuleResourceService;

	@Autowired
	private ISysRoleModules sysRoleModulesService;

	@Autowired
	private ISysResource sysResourceService;

	/**
	 * @Title: getSysModuleById
	 * @Description: 根据id获取系统模块信息
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getSysModuleById", method = RequestMethod.POST)
	public ResponseBase<SysModuleRes> getSysModuleById(
			@RequestBody SysModuleReq req) {
		ResponseBase<SysModuleRes> resp = new ResponseBase<SysModuleRes>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			SysModule sysModule = sysModuleService.findById(req.getId());
			
			SysModuleRes singleResp=new SysModuleRes();
			singleResp.setSysModule(sysModule);
			List<SysModuleResource> sysModuleResources = sysModuleResourceService
					.getByModuleId(sysModule.getId());
			singleResp.setSysModuleResources(sysModuleResources);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setResult(singleResp);
		} catch (Exception ex) {
			logger.error(ex.getMessage(),ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: getSysModuleList
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getSysModuleList", method = RequestMethod.POST)
	public ResponseBase<List<SysModuleRes>> getSysModuleList(
			@RequestBody SysModuleReq req) {
		ResponseBase<List<SysModuleRes>> resp = new ResponseBase<List<SysModuleRes>>();
		HqlFilter hqlFilter=new HqlFilter();
		if(StringUtils.isNotEmpty(req.getName())){
			hqlFilter.addEQFilter("name", req.getName());
		}
		hqlFilter.addSort("id");
		hqlFilter.addOrder("desc");
		try {
			List<SysModule> sysModuleList = sysModuleService.findByFilter(hqlFilter,
					req.getCurPage(), req.getPageSize());
			
			List<SysModuleRes> respList=new ArrayList<SysModuleRes>();
			// 根据模块id查询资源
			if (sysModuleList != null && !sysModuleList.isEmpty()) {
				SysModuleRes singleResp=null;
				for (SysModule sysModule : sysModuleList) {
					singleResp=new SysModuleRes();
					singleResp.setSysModule(sysModule);
					List<SysModuleResource> sysModuleResources = sysModuleResourceService
							.getByModuleId(sysModule.getId());
					singleResp.setSysModuleResources(sysModuleResources);
					respList.add(singleResp);
				}
				Long total = sysModuleService.countByFilter(hqlFilter);
				resp.setSize(total);
				resp.setResultCode(StatusCode.SUCCESS.key());
			}
			resp.setResult(respList);

		} catch (Exception ex) {
			logger.error(ex.getMessage(),ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: getAllSysModuleName
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getAllSysModuleName", method = RequestMethod.POST)
	public ResponseBase<List<SysModule>> getSysModuleNameList(
			@RequestBody SysModuleReq req) {
		ResponseBase<List<SysModule>> resp = new ResponseBase<List<SysModule>>();
		HqlFilter hqlFilter=new HqlFilter();
		hqlFilter.addSort("id");
		hqlFilter.addOrder("desc");
		
		try{
			List<SysModule> sysModuleList = sysModuleService.findByFilter(hqlFilter);	
			resp.setResult(sysModuleList);

		} catch (Exception ex) {
			logger.error(ex.getMessage(),ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}
	
	/**
	 * @Title: saveSysModule
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/saveSysModule", method = RequestMethod.POST)
	public ResponseBase<SysModule> saveSysModule(@RequestBody SysModuleReq req) {
		ResponseBase<SysModule> resp = new ResponseBase<SysModule>();
		try {
			SysModule model = new SysModule();
			model.setCode(req.getCode());
			model.setCreatedts( this.getCurrentTime() );
			model.setCreator(this.getAccount());
			model.setDescp(req.getDescp());
			model.setName(req.getName());
			Long  retId = sysModuleService.add(model);
			
			if (retId != null) {
				SysModuleResource sysModuleResource = null;
				String[] resourceIdss = req.getResourceIds().split(",");
				for (int i = 0, len = resourceIdss.length; i < len; i++) {
					String resourceId = resourceIdss[i];

					sysModuleResource = new SysModuleResource();
					sysModuleResource.setModuleId(retId);
					sysModuleResource.setResourceId(Long.parseLong(resourceId));
					sysModuleResourceService.add(sysModuleResource);
				}
				
				model.setId(retId);
				resp.setResult(model);
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("添加成功");
			} else {
				resp.setResultCode(StatusCode.ERROR.key());
				resp.setMsg("添加失败");
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(),ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: updateSysModule
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/updateSysModule", method = RequestMethod.POST)
	public ResponseBase<SysModule> updateSysModule(
			@RequestBody SysModuleReq req) {
		ResponseBase<SysModule> resp = new ResponseBase<SysModule>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}
			SysModule model = sysModuleService.findById(req.getId());
			model.setCode(req.getCode());
			model.setDescp(req.getDescp());
			model.setName(req.getName());
			sysModuleService.update(model);

		
				// 修改模块与资源关系，先删除再添加
				List<SysModuleResource> relSysModuleResources = sysModuleResourceService
						.getByModuleId(model.getId());
				if (relSysModuleResources != null
						&& !relSysModuleResources.isEmpty()) {
					for (SysModuleResource sysModuleResource : relSysModuleResources) {
						sysModuleResourceService.delete(sysModuleResource.getId());
					}
				}

				// 模块与资源关系
				Long moduleId = model.getId();
				SysModuleResource sysModuleResource = null;
				String[] resourceIdss = req.getResourceIds().split(",");
				for (int i = 0, len = resourceIdss.length; i < len; i++) {
					sysModuleResource = new SysModuleResource();
					String resourceId = resourceIdss[i];
					sysModuleResource.setModuleId(moduleId);
					sysModuleResource.setResourceId(Long.parseLong(resourceId));
					sysModuleResourceService.add(sysModuleResource);
				}
				resp.setResult(model);			
				resp.setResultCode(StatusCode.SUCCESS.key());
				resp.setMsg("修改成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(),ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: deleteSysModule
	 * @Description: TODO
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteSysModule", method = RequestMethod.POST)
	public ResponseBase<SysModule> deleteSysModule(@RequestBody SysModuleReq req) {
		ResponseBase<SysModule> resp = new ResponseBase<SysModule>();
		try {
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				return resp;
			}

			// 删除模块与资源关系
			List<SysModuleResource> relSysModuleResources = sysModuleResourceService
					.getByModuleId(req.getId());
			if (relSysModuleResources != null
					&& !relSysModuleResources.isEmpty()) {
				for (SysModuleResource sysModuleResource : relSysModuleResources) {
					sysModuleResourceService.delete(sysModuleResource.getId());
				}
			}
			SysModule ret = sysModuleService.delete(req.getId());

			resp.setResult(ret);
			resp.setResultCode(StatusCode.SUCCESS.key());
			resp.setMsg("删除成功");
		} catch (Exception ex) {
			logger.error(ex.getMessage(),ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * @Title: getAllModule
	 * @Description: 获取所有系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getAllModule", method = RequestMethod.POST)
	public ResponseBase<List<SysModuleRes>> getAllModule(
			@RequestBody SysModuleReq req) {
		ResponseBase<List<SysModuleRes>> resp = new ResponseBase<List<SysModuleRes>>();
		HqlFilter hqlFilter=new HqlFilter();
		try {
			List<SysModule> sysModuleList = sysModuleService.findByFilter(hqlFilter,
					req.getCurPage(), req.getPageSize());
			
			List<SysModuleRes> respList=new ArrayList<SysModuleRes>();
			// 根据模块id查询资源
			if (sysModuleList != null && !sysModuleList.isEmpty()) {
				SysModuleRes singleResp=null;
				for (SysModule sysModule : sysModuleList) {
					singleResp=new SysModuleRes();
					singleResp.setSysModule(sysModule);
					respList.add(singleResp);
				}
			}
			resp.setResult(respList);
		} catch (Exception ex) {
			logger.error(ex.getMessage(),ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}
}
